package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.SyncUploadAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.entity.YNAlbumResponse;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class CardSyncUploadActivity extends Activity {
    private ListView cardsnyc_listview;
    private TextView cardsnyc_sure;
    public static ArrayList<YNAlbum> tagList = new ArrayList<YNAlbum>();
    private Gson gson;
    private BaseApplication application;
    private HttpConfig mHttpConfig;
    private SyncUploadAdapter mSyncUploadAdapter;
    private List<YNAlbum> YNAlbumlist;
    private SharedPreferences.Editor editor;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;
    private ProgressDialog mProgressDialog;
    private String groupIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_memory_card_snycupload);
        init();
        initView();
        getAlbumListById(application.getCurID());
    }

    private void init() {
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        gson = new Gson();
        application = (BaseApplication) getApplication();
        mHttpConfig = new HttpConfig(CardSyncUploadActivity.this);
        registerBroadcastReceiver();
        tagList.clear();
    }

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.updataSyncUploadok);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.updataSyncUploadok:
                    cardsnyc_sure.setTextColor(getResources().getColor(R.color.user_color_green));
                    break;
            }
        }
    };

    private long getTotalLenth() {
        long totalSize = 0;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            String address = SelectedImg.mSelectedImage.get(i);
            File uploadImg = new File(address);
            long imgSize = uploadImg.length();
            totalSize += imgSize;
        }
        return totalSize;
    }

    private void initView() {
        cardsnyc_sure = (TextView) findViewById(R.id.cardsnyc_sure);
        cardsnyc_listview = (ListView) findViewById(R.id.cardsnyc_listview);
        cardsnyc_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tagList.size() == 0) {
                    Toast.makeText(CardSyncUploadActivity.this, "请选择圈子", Toast.LENGTH_SHORT).show();
                    return;
                }
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < tagList.size(); j++) {
                    builder.append(tagList.get(j).getGroupid() + ",");
                }
                String taglistr = builder.toString();
                groupIds = taglistr.substring(0, taglistr.length() - 1);
                long upstorge = getTotalLenth();
                String fsize = SizeFormat.formatSize(upstorge);
                mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {
                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        doUpImg(false);
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            doUpImg(false);
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                }
                //doUpImg(false);
            }
        });
        findViewById(R.id.cardsync_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(CardSyncUploadActivity.this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupIds);
        String mid = null;
        for (int i = 0; i < tagList.size(); i++) {
            String gimid = tagList.get(i).getGimid();
            if (mid == null) {
                mid = gimid;
            } else {
                mid = gimid + "," + mid;
            }
        }
        mIntent.putExtra(ACTIONs.aGimid, mid);
        mIntent.putExtra(ACTIONs.aType, getIntent().getBooleanExtra(ACTIONs.aType, false));
        mIntent.putExtra(ACTIONs.aPush, getIntent().getStringExtra(ACTIONs.aPush));
        mIntent.putExtra(ACTIONs.aIsOfficial, getIntent().getIntExtra(ACTIONs.aIsOfficial, 0));
        mIntent.putExtra(ACTIONs.aGname, "");
        mIntent.putExtra(ACTIONs.aContent, getIntent().getStringExtra(ACTIONs.aContent));
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upstorage, getIntent().getStringExtra(ACTIONs.upstorage));
        mIntent.putExtra(ACTIONs.upismemorycard, getIntent().getIntExtra(ACTIONs.upismemorycard, 0));
        mIntent.putExtra(ACTIONs.uptags, getIntent().getStringExtra(ACTIONs.uptags));
        mIntent.putExtra(ACTIONs.upaudio, getIntent().getStringExtra(ACTIONs.upaudio));
        mIntent.putExtra(ACTIONs.upmemorytime, getIntent().getStringExtra(ACTIONs.upmemorytime));
        mIntent.putExtra(ACTIONs.upplace, getIntent().getStringExtra(ACTIONs.upplace));
        mIntent.putExtra(ACTIONs.upaudiotime, getIntent().getStringExtra(ACTIONs.upaudiotime));
        mIntent.putExtra(ACTIONs.upcoverUrl, getIntent().getStringExtra(ACTIONs.upcoverUrl));
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
        tagList.clear();
        Intent intent = getIntent();
        intent.putExtra("sync", "sync");
        setResult(MemoryCardEditActivity.TAKE_SYNC, intent);// 返回参数
        finish();
    }


    private void getAlbumListById(int uId) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(uId));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowPhoto))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumResponse resGroup = gson.fromJson(s, YNAlbumResponse.class);
                        if (resGroup != null && ReqUtils.isSuccess(resGroup.getCode())) {
                            // 通知列表更新
                            YNAlbumlist = resGroup.getData();
                            mSyncUploadAdapter = new SyncUploadAdapter(CardSyncUploadActivity.this, YNAlbumlist);
                            cardsnyc_listview.setAdapter(mSyncUploadAdapter);
                            mSyncUploadAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(CardSyncUploadActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
        LiteHttp.newApacheHttpClient(mHttpConfig).executeAsync(req);
    }

    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(true);
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }


    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
